package com.example.itcacp.repository.mybatis;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.BrowseHistory;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 浏览记录Mapper层
 * */
@Repository
public interface BrowseHistoryMapper extends BaseMapper<BrowseHistory> {


    // 专门用于项目浏览量查询的方法
    @Select("SELECT COUNT(*) FROM itcacp.pc_browse_history " +
            "WHERE target_id = #{contentId} AND target_type = 'PROJECT'")
    Long findBrowseHistoryByProjectId(Long contentId);

    /**
     * 查询对应内容浏览数
     * COUNT（字段）: 计数
     * GROUP_CONCAT(字段) : 合并
     * */
    @Select( "SELECT COUNT(*) FROM itcacp.pc_browse_history WHERE " +
            "target_id = #{contentId} AND target_type = #{contentType}" )
    Long findBrowseHistory (@Param("contentId") Long contentId, @Param("contentType") String contentType);


    /**
     * 查询用户浏览记录，相同内容只保留最新一条
     */
    @Select({
            "SELECT bh.* FROM pc_browse_history bh JOIN "+
            "   (SELECT target_id, target_type, MAX(created_at) AS max_created_at"+
            "   FROM pc_browse_history"+
            "   WHERE user_id = #{userId}"+
            "   GROUP BY target_id, target_type"+
            ") latest ON bh.target_id = latest.target_id " +
                    "AND bh.target_type = latest.target_type " +
                    "AND bh.created_at = latest.max_created_at " +
                    "WHERE bh.user_id = #{userId} "
    })
    List<BrowseHistory> selectLatestByUserId(@Param("userId") Long userId);
// +
//         "ORDER BY bh.created_at DESC"

    /**
     * 自定义查询方法，显式映射时间字段
     */
    @Select("SELECT history_id, user_id, target_id, target_type, created_at " +
            "FROM pc_browse_history ${ew.customSqlSegment}")
    @Results({
            @Result(column = "created_at", property = "created_at"),
            // 其他字段映射...
    })
    List<BrowseHistory> selectWithTimeMapping(@Param("ew") Wrapper<BrowseHistory> wrapper);

    @Select ( "SELECT * FROM pc_browse_history WHERE target_type = #{type}" )
    List<BrowseHistory> selectListByType(String type);
}
